/**
 * @Title:  语言选择组件
 * @Date:   2018-2-2
 * @Author: wuji
 */
require("./ie9-classlist.js");
require("../css/index.less");
const htmlCon = require("../index.html");



function IolLanguageSelect(opts){
	// 1 ctn
	if(opts.el){
		if(typeof opts.el == "string"){
			this.el =  document.getElementById(opts.el);
			if(!this.el){ console.log("提供的容器元素不存在!"); return false;}
		}else if(opts.el.nodeType == 1){
			this.el = opts.el;
		}
	}else{
		console.log("请提供容器元素!"); return false;
	}
	
	// 2 langs
	this.langs = opts.languages ? opts.languages : this.dltLanguages;
	if(this.langs.length < 2){ console.error("请至少提供2种语言!"); return false; }
	this.ids   = this.getIds();
	
	// 3 origin target
	this.originLang =  ""; 		// 源语言
	this.originId = 0;			// 源语言id
	this.targetLang = "";		// 目标语言
	this.targetId = 0; 			// 目标语言id
	this.activeLang = "";		// 当前是源语言还是目标语言
	this.options = opts;
	// 源语言 是否有 自动选择 项
	this.autoLang = opts.autoLang ? opts.autoLang : "自动检测"; 	// 自动检测名称
	this.hasAutocheck = opts.hasAutocheck ? opts.hasAutocheck : false;
	// 源语言 是否 含有 "源语言"选项; 目标语言是否含有 "目标语言"选项
	this.hasEmpty = opts.hasEmpty ? opts.hasEmpty : true;
	this.emptyOrigin = "源语言";
	this.emptyTarget = "目标语言";
	this.setOrigin(opts.originLang);
	this.setTarget(opts.targetLang);

	// 展开/收起参数
	if(opts.expandFlag) {
		this.expand = {
			targetClass: "iol-show",
			targetBtnCon: "收起",
			originClass: "iol-show",
			originBtnCon: "收起"
		};
	} else {
		this.expand = {
			targetClass: "",
			targetBtnCon: "展开",
			originClass: "",
			originBtnCon: "展开"
		};
	}

	
	// 4 语言分组
	this.group = opts.autoGroup ? this._calGroup(opts.groupNum) : (opts.group ? opts.group : this.dltGroup);
	this.createLangGroup();
	
	// 5 实例个数++
	IolLanguageSelect.prototype.instanceCount += 1;		
	
	// 6 init html
	this.initHtml();
	this.render();
	this.initEvent();
};

// 默认分组
IolLanguageSelect.prototype.dltGroup = ["ABC", "DEFG", "HIJKLMN", "OPQRST", "UVWX", "YZ"];

// 默认语言列表
IolLanguageSelect.prototype.dltLanguages = [
	{id: 0,  langName: "阿拉伯语", 		langAlpha: "a"},
	{id: 1,  langName: "爱沙尼亚语", 		langAlpha: "a"},
	{id: 2,  langName: "保加利亚语", 		langAlpha: "b"},
	{id: 3,  langName: "波兰语", 		langAlpha: "b"},
	{id: 4,  langName: "丹麦语", 		langAlpha: "d"},
	{id: 5,  langName: "德语", 			langAlpha: "d"},
	{id: 6,  langName: "俄语", 			langAlpha: "e"},
	{id: 7,  langName: "法语", 			langAlpha: "f"},
	{id: 8,  langName: "芬兰语", 		langAlpha: "f"},
	{id: 9,  langName: "韩语", 		 	langAlpha: "h"},
	{id: 10, langName: "荷兰语", 		langAlpha: "h"},
	{id: 11, langName: "捷克语", 		langAlpha: "j"},
	{id: 12, langName: "罗马尼亚语", 		langAlpha: "l"},
	{id: 13, langName: "葡萄牙语", 		langAlpha: "p"},
	{id: 14, langName: "日语", 			langAlpha: "r"},
	{id: 15, langName: "瑞典语", 		langAlpha: "r"},
	{id: 16, langName: "斯洛文尼亚语", 	langAlpha: "s"},
	{id: 17, langName: "泰语", 			langAlpha: "t"},
	{id: 18, langName: "西班牙语", 		langAlpha: "x"},
	{id: 19, langName: "希腊语", 		langAlpha: "x"},
	{id: 20, langName: "匈牙利语", 		langAlpha: "x"},
	{id: 21, langName: "英文", 			langAlpha: "y", isCommon: true},
	{id: 22, langName: "意大利语", 		langAlpha: "y"},
	{id: 23, langName: "越南语", 		langAlpha: "y"},
	{id: 24, langName: "粤语", 			langAlpha: "y"},
	{id: 25, langName: "中文", 			langAlpha: "z", isCommon: true},
	{id: 26, langName: "中文繁体", 		langAlpha: "z"}
];

// 实例的个数
IolLanguageSelect.prototype.instanceCount = 0;

IolLanguageSelect.prototype.initHtml = function(){
	// 初始化 html
	var div = document.createElement("div");
	div.className = "iol-language-select";
	div.innerHTML = htmlCon;
	this.el.appendChild(div);
};

IolLanguageSelect.prototype.render = function(){
	// 渲染
	this.renderOperation();
	this.renderOrigin();
	this.renderTarget();
};

IolLanguageSelect.prototype.renderOperation = function(){
	// 渲染操作栏
	// 1 源语言
	this.el.querySelector(".origin-lang").innerHTML = this.originLang;
	this.el.querySelector(".js-origin").classList.remove("active");
	// 2 目标语言
	this.el.querySelector(".target-lang").innerHTML = this.targetLang;
	this.el.querySelector(".js-target").classList.remove("active");
	
	// 3 禁用 语言互换
	// 1 如果源语言 是 自动检测; 2 如果 originId 或者 targetId < 0;
	var exchangeEl = this.el.querySelector(".exchange");
	if(this.originLang == this.autoLang || this.originId < 0 || this.targetId < 0) {
		exchangeEl.classList.add("disabled");
	}else{
		exchangeEl.classList.remove("disabled");
	}
};

IolLanguageSelect.prototype.renderOrigin = function(){
	// 渲染源语言
	// 1 常用语言
	var oftenHtml = this.getHtmlOfOften(this.getOftenLangs(), "origin");
	this.el.querySelector(".origin-langs .langs-often").innerHTML = oftenHtml;

	// 2 语言列表
	var Langshtml = this.getHtmlOfLangs(this.groupLangs, "origin");
	this.el.querySelector(".origin-langs .language-list").innerHTML = Langshtml;

	var expandBtn = this.el.querySelector(".origin-langs .iol-btn-expand");
	expandBtn.innerHTML = this.expand.originBtnCon;
	this.el.querySelector(".origin-langs").className = "origin-langs " + this.expand.originClass;
};

IolLanguageSelect.prototype.renderTarget = function(){
	// 渲染目标语言
	// 1 常用语言
	var oftenHtml = this.getHtmlOfOften(this.getOftenLangs(), "target");
	this.el.querySelector(".target-langs .langs-often").innerHTML = oftenHtml;
	// 2 语言列表
	var Langshtml = this.getHtmlOfLangs(this.groupLangs, "target");
	this.el.querySelector(".target-langs .language-list").innerHTML = Langshtml;

	expandBtn = this.el.querySelector(".target-langs .iol-btn-expand");
	expandBtn.innerHTML = this.expand.targetBtnCon;
	this.el.querySelector(".target-langs").className = "target-langs " + this.expand.originClass;
};

IolLanguageSelect.prototype.getHtmlOfLangs = function(groupLangs, type){
	// 获取所有语言的html, 
	// groupLangs: 已经分组的语言列表, type: "origin/target", 源语言和目标语言
	// 这么区分主要是为了标识不可用项
	var html = [], html2 = [], key, j, item, item2, len = this.langs.length, len2;
	for(key in groupLangs){
		item = groupLangs[key];
		len2 = item.length;
		html2 = [];
		html2.push('<ul><li class="language-class">'+ key +'</li>')
		
		for(j = 0; j < len2; j++){
			item2 = item[j];
			
			if(type == "target" && item2.langName == this.originLang){
				html2.push('<li><a href="javascript:;" data-id="'+ item2.id +'" class="disabled lang">'+ item2.langName +'</a></li>');
			}else if(type == "target" && item2.langName == this.targetLang){
				html2.push('<li><a href="javascript:;" data-id="'+ item2.id +'" class="active lang">'+ item2.langName +'</a></li>');
			}else if(type == "origin" && item2.langName == this.originLang){
				html2.push('<li><a href="javascript:;" data-id="'+ item2.id +'" class="active lang">'+ item2.langName +'</a></li>');
			}else if(type == "origin" && item2.langName == this.targetLang){
				html2.push('<li><a href="javascript:;" data-id="'+ item2.id +'" class="disabled lang">'+ item2.langName +'</a></li>');
			}else{
				html2.push('<li><a href="javascript:;" data-id="'+ item2.id +'" class="lang">'+ item2.langName +'</a></li>');
			}
		}
		html2.push("</ul>");
		
		html.push(html2.join(""));
	}
	return html.join("");
};

IolLanguageSelect.prototype.getHtmlOfOften = function(langs, type){
	// 获取常用语言的html, 
	// langs: 常用语言列表, type: "origin/target", 源语言和目标语言
	// 这么区分主要是为了标识不可用项
	var html = [], i, item, len = langs.length;
	
	// 是否有 自动检测 项
	if(type == "origin" && this.hasAutocheck){
		var cName = this.originLang == this.autoLang ? "active" : "";
		html.push('<li><a href="javascript:;" data-id="-1" class="lang '+ cName +'">'+ this.autoLang +'</a></li>');
	}
	
	// 是否有 empty 项
	if(this.hasEmpty && type == "origin"){
		var cName = this.originLang == this.emptyOrigin ? "active" : "";
		html.push('<li><a href="javascript:;" data-id="-3" class="lang '+ cName +'">'+ this.emptyOrigin +'</a></li>');
	}else if(this.hasEmpty && type == "target"){
		var cName = this.targetLang == this.emptyTarget ? "active" : "";
		html.push('<li><a href="javascript:;" data-id="-4" class="lang '+ cName +'">'+ this.emptyTarget +'</a></li>');
	}
	
	for(i = 0; i < len; i++){
		item = langs[i];
		if(type == "target" && item.langName == this.originLang){
			html.push('<li><a href="javascript:;" data-id="'+ item.id +'" class="disabled lang">'+ item.langName +'</a></li>');
		}else if(type == "target" && item.langName == this.targetLang){
			html.push('<li><a href="javascript:;" data-id="'+ item.id +'" class="active lang">'+ item.langName +'</a></li>');
		}else if(type == "origin" && item.langName == this.targetLang){
			html.push('<li><a href="javascript:;" data-id="'+ item.id +'" class="disabled lang">'+ item.langName +'</a></li>');
		}else if(type == "origin" && item.langName == this.originLang){
			html.push('<li><a href="javascript:;" data-id="'+ item.id +'" class="active lang">'+ item.langName +'</a></li>');
		}else{
			html.push('<li><a href="javascript:;" data-id="'+ item.id +'" class="lang">'+ item.langName +'</a></li>');
		}
	}
	return html.join("");
};

IolLanguageSelect.prototype._calGroup = function(groupNum){
	// 根据 groupNum: 组个数(默认为6个), 计算分组, 使得各个分组含有的项数尽量相等
	var totalNum = this.langs.length; 		// 总语言数
	groupNum = groupNum ? groupNum : 6;		// 组个数
	
	// 1 先创建一个包含26个字母为key的对象, 值都为0: {'A': 0, 'B': 0,...,'Z': 0}
	var i = "A".charCodeAt(0),	len = "Z".charCodeAt(0) + 1,
		alphaGroup = {};
	for(; i < len ; i++){
		alphaGroup[String.fromCharCode(i)] = 0;
	}
	
	// 2 计算语言中 对应各个字母语言的数量
	len = this.langs.length;
	for( i = 0; i < len; i++){
		alphaGroup[this.langs[i].langAlpha.toUpperCase()]++;
	}
	
	// 3 
	var averageNum = parseInt(totalNum/groupNum),	// 平均值
		newGroup = [];								// 将要生成的新的group
		num1 = 0, num2 = 0;
	i = "A".charCodeAt(0),	len = "Z".charCodeAt(0) + 1;
	var j = i, curNum = 0, tmpStr = [], k = 0,
		startIndex = i, endIndex = 0;		// 每次的起始索引 和 结束索引
	for(; i < len ; i++){
		curNum = alphaGroup[String.fromCharCode(i)];
		num2 += curNum;
		num1 = num2 - curNum;
		
		if(num2 >= averageNum){
			// 分界点
			if(averageNum - num1 >= num2 - averageNum){
				endIndex = i;
			}else{
				endIndex = i == j ? j : i - 1;
			}
			
			// 计算重开始startIndex, 到 endIndex的所有字符串
			for(k = startIndex; k <= endIndex; k++){
				tmpStr.push(String.fromCharCode(k));
			}
			newGroup.push(tmpStr.join(""));
			
			// 重新初始化
			tmpStr = [];
			startIndex = endIndex + 1;
			i = startIndex - 1;
			num2 = 0;
			
			// 一旦 组数  =  groupNum - 1, 把剩下的全部加入到最后一个组
			if(newGroup.length == groupNum - 1){
				for(k = startIndex; k <= 'Z'.charCodeAt(0); k++){
					tmpStr.push(String.fromCharCode(k));
				}
				newGroup.push(tmpStr.join(""));
				break;
			}
		}
		
		if(i == len - 1){
			// 把剩下的全部加入到最后一个组
			for(k = startIndex; k <= 'Z'.charCodeAt(0); k++){
				tmpStr.push(String.fromCharCode(k));
			}
			newGroup.push(tmpStr.join(""));
		}
	}
	
	return newGroup;
};

IolLanguageSelect.prototype._setGroup = function(group){
	// 设置分组信息
	// 确定全部大写
	var i, item, len = this.group.length;
	for( i = 0; i < len; i++){
		this.group[i] = this.group[i].toUpperCase();
	}
	
	// groupNum = [3, 7, 14, 20, 24, 26]
	var groupNum = [], total = 0;
	for( i = 0; i < len; i++){
		total += this.group[i].length;
		groupNum[i] = total;
	}
	
	// this.group2 = {'A': 'ABC', 'B': 'ABC'...}
	start = 'A'.charCodeAt(0), len = 'Z'.charCodeAt(0) + 1;
	this.group2 = {};
	var tmpIndex, j, len2 = groupNum.length;
	for(i = start; i < len; i++){
		tmpIndex = i - start;
		for(j = 0; j < len2; j++){
			if(tmpIndex < groupNum[j]){
				this.group2[String.fromCharCode(i).toUpperCase()] = this.group[j];
				break;
			}
		}
	}
};

IolLanguageSelect.prototype.setGroup = function(group){
	if(group && Array.isArray(group)){
		this.group = group;
		this.createLangGroup();
	}
};

IolLanguageSelect.prototype.createLangGroup = function(){
	// 根据分组信息, 把所有语言分成组
	// 生成group2
	this._setGroup();
	
	var groupLangs = {};
	var i, item, len = this.group.length;
	for(i = 0; i < len; i++){
		groupLangs[this.group[i]] = [];
	}
	
	len = this.langs.length;
	for(i = 0; i < len; i++){
		item = this.langs[i];
		groupLangs[this.group2[item.langAlpha.toUpperCase()]].push(item);
	}
	
	this.groupLangs = groupLangs;
};

IolLanguageSelect.prototype.setOrigin = function(lang){
	// 设置源语言(可以用语言名称或语言id来设置)
	if(typeof lang == "number"){
		// 根据语言Id来设置
		var curIndex 	= this.getIndexOfLang(lang),
			curItem 	= this.langs[curIndex];
		if(curItem){
			this.originLang = curItem.langName;
			this.originId   = lang;
		}else{
			console.error("id不在当前语言列表中");
		}
	}else if(typeof lang == "string" || !lang){
		// 根据名称来设置
		lang = lang ? lang : this.emptyOrigin;
		this.originLang = lang;
	
		var curIndex 	= this.getIndexOfLang(lang);
		if(curIndex < 0){
			console.warn("您选择的源语言: " + lang + ", 在语言列表中找不到对应项.");
			this.originId = -1;
		}else{
			this.originId 	= this.langs[curIndex].id;
		}
	}
};

IolLanguageSelect.prototype.getOrigin = function(lang){
	// 获取源语种
	return this.originLang;
};

IolLanguageSelect.prototype.getOriginObj = function(lang){
	// 获取源语种对象
	return this.getIndexOfLang(this.originLang, true);
};

IolLanguageSelect.prototype.getTarget = function(lang){
	// 获取目标语种
	return this.targetLang;
};

IolLanguageSelect.prototype.getTargetObj = function(lang){
	// 获取目标语种对象
	return this.getIndexOfLang(this.targetLang, true);
};

IolLanguageSelect.prototype.setTarget = function(lang){
	// 设置目标语言(根据名称和Id)
	if(typeof lang == "number"){
		// 根据语言Id来设置
		var curIndex 	= this.getIndexOfLang(lang),
			curItem 	= this.langs[curIndex];
		if(curItem){
			this.targetLang = curItem.langName;
			this.targetId   = lang;
		}else{
			console.error("id不在当前语言列表中");
		}
	}else if(typeof lang == "string" || !lang){
		lang = lang ? lang : this.emptyTarget;
		this.targetLang = lang;
		
		var curIndex 	= this.getIndexOfLang(lang);
		if(curIndex < 0){
			console.warn("您选择的目标语言: " + lang + ", 在语言列表中找不到对应项.");
			this.targetId = -2;
		}else{
			this.targetId 	= this.langs[curIndex].id;
		}
	}
};

IolLanguageSelect.prototype.getLanguages = function(){
	// 获取语言列表
	return this.langs;
};

IolLanguageSelect.prototype.addLanguages = function(langs){
	// 增加语言列表
	if(!Array.isArray(langs)){ langs = [langs]; }
	
	var i, item, len = langs.length, 
		startId = this.getAvailableId(), tmpLangs = [], preId;
	for(i = 0; i < len; i++){
		item = langs[i];
		
		preId = this.getIndexOfLang(item.langName);
		if(preId == -1){
			tmpLangs.push({
				id: startId + i,
				langName: item.langName,
				langAlpha: item.langAlpha,
				isCommon: item.isCommon ? true : false
			});
		}else if(preId == -2){
			console.log("请加入字符串格式的语言!");
		}else{
			console.log("该语言已经加入, 请勿重复加入!");
		}
	}
	
	// 加入到this.langs
	this.langs = this.langs.concat(tmpLangs);
	this.ids = this.getIds();
	
	// 分组
	if(this.options.autoGroup){
		this.group = this._calGroup();
	}
	this.createLangGroup();
};

IolLanguageSelect.prototype.rmLanguages = function(langs){
	// 删除指定的语言
	if(!Array.isArray(langs)){ langs = [langs]; }
	
	var i, item, len = langs.length, tmpIndex;
	for(i = 0; i < len; i++){
		// item: 有可能是id, 也有可能是语言名称
		tmpIndex = this.getIndexOfLang(langs[i]);
		if(tmpIndex >= 0){
			this.langs.splice(tmpIndex, 1);
		}else{
			console.log("要删除的语言: " + langs[i] + ", 不存在");
		}
	}
	
	this.ids = this.getIds();
};

// 常用语言相关
IolLanguageSelect.prototype.getOften = function(langs){
	// 获取常用语言列表
	var oftenLangs = [];
	this.langs.forEach(function(item, index, array){
		if(item.isCommon){ oftenLangs.push(item); }
	});
	
	return oftenLangs;
};	

IolLanguageSelect.prototype.setOften = function(langs){
	// 重新设置常用语言列表
	this.langs.forEach(function(item, index, array){
		item.isCommon = false;
	});
	
	this.addOften(langs);
};	
	
IolLanguageSelect.prototype.addOften = function(langs){
	// 增加常用语言
	if(!Array.isArray(langs)){ langs = [langs]; }
	
	var i, item, len = langs.length, tmpIndex;
	for(i = 0; i < len; i++){
		// item: 有可能是id, 也有可能是语言名称
		tmpIndex = this.getIndexOfLang(langs[i]);
		if(tmpIndex >= 0){
			this.langs[tmpIndex].isCommon = true;
		}else{
			console.log("要增加的常用语言: " + langs[i] + ", 不在当前语言列表中");
		}
	}
};

IolLanguageSelect.prototype.rmOften = function(langs){
	// 删除常用语言
	if(!Array.isArray(langs)){ langs = [langs]; }
	
	var i, item, len = langs.length, tmpIndex;
	for(i = 0; i < len; i++){
		// item: 有可能是id, 也有可能是语言名称
		tmpIndex = this.getIndexOfLang(langs[i]);
		if(tmpIndex >= 0){
			this.langs[tmpIndex].isCommon = false;
		}else{
			console.log("要删除的常用语言: " + langs[i] + ", 不在当前语言列表中");
		}
	}
};

IolLanguageSelect.prototype.getIndexOfLang = function(param, type){
	// 获取某语言的索引, 如果没有, 则表示该语言还未加入到语言列表
	// param: id或者语言名称
	// type: true: 获取整个语言对象
	if(typeof param != "string" && typeof param != "number"){ return -2; }
	
	var i, len = this.langs.length, item,
		key = (typeof param == "number") ? "id" : "langName";
	for(i = 0; i < len; i++){
		item = this.langs[i];
		
		if(item[key] == param){
			return type ? item : i;
		}
	}
	return -1;
};

IolLanguageSelect.prototype.getIds = function(){
	// 获取所有语言ids
	var i, len = this.langs.length, ids = [];
	for(i = 0; i < len; i++){
		ids.push(this.langs[i].id);
	}
	ids.sort(compare);
	function compare(val1, val2){
		return val1 - val2;
	}
	
	return ids;
};

IolLanguageSelect.prototype.getAvailableId = function(){
	// 获取可用的语言Id
	return this.ids[this.ids.length - 1] + 1;
};

IolLanguageSelect.prototype.getOftenLangs = function(){
	// 获取常用语言列表
	var i, item, len = this.langs.length, oftenLangs = [];
	for(i = 0; i < len; i++){
		item = this.langs[i];
		if(item.isCommon){ oftenLangs.push(item); }
	}
	return oftenLangs;
};

IolLanguageSelect.prototype.showOriginLangs = function(){
	// 显示源语言列表
	this.el.querySelector(".js-target").classList.remove("active");
	this.el.querySelector(".target-langs").style.display = "none";
	var langBtn = this.el.querySelector(".js-origin"),
		langs   = this.el.querySelector(".origin-langs");
	langs.style.display = "block";
	langBtn.classList.add("active");

	this.activeLang = "origin";
	
	this.showUpOrDown();
};

IolLanguageSelect.prototype.showTargetLangs = function(){
	// 显示目标语言列表
	this.el.querySelector(".js-origin").classList.remove("active");
	this.el.querySelector(".origin-langs").style.display = "none";
	var langBtn = this.el.querySelector(".js-target"),
		langs   = this.el.querySelector(".target-langs");
	langs.style.display = "block";
	langBtn.classList.add("active");

	this.activeLang = "target";

	this.showUpOrDown();
};

IolLanguageSelect.prototype.showUpOrDown = function(opts){
	// 计算是向上显示, 还是向下显示
	// 1 计算 容器离浏览器底部的距离
	var ctnBt = window.innerHeight - this.el.getBoundingClientRect().bottom;
	// 2 语言列表的高度
	var tmpLangs = this.el.querySelector(".origin-langs");
	if(tmpLangs.style.display != "block"){
		tmpLangs = this.el.querySelector(".target-langs");
	}
	var langsHeight = tmpLangs.offsetHeight, direction = "down";
	if(langsHeight > ctnBt){
		direction = "up";
	}

	// 显示容器 方向
	var ctn = this.el.querySelector(".iol-language-select");
	if(direction == "up"){
		ctn.classList.add("up");
	}else{
		ctn.classList.remove('up');
	}
	ctn.style.zIndex = 100;

	// 计算
};

IolLanguageSelect.prototype.closeLangs = function(){
	// 关闭语言选择
	this.el.querySelector(".js-origin").classList.remove("active");
	this.el.querySelector(".js-target").classList.remove("active");
	this.el.querySelector(".origin-langs").style.display = "none";
	this.el.querySelector(".target-langs").style.display = "none";
	
	// z-index
	this.el.querySelector(".iol-language-select").style.zIndex = 0;
};

IolLanguageSelect.prototype.exchange = function(){
	// 交互语言
	if(this.exchangeStatus == true){ return false; }
	this.exchangeStatus = true;
	
	// 1 交互动画
	var operateCtn = this.el.querySelector(".translate-operation");
	operateCtn.classList.add("exchanging");
	// 为了便于修改样式, 要修改css中 .exchanging .origin .in 的 left值
	var outWidth = operateCtn.offsetWidth,
		inWidth	 = operateCtn.querySelector(".origin").offsetWidth;
	operateCtn.querySelector(".origin .in").style.left = outWidth - inWidth + "px";
	operateCtn.querySelector(".target .in").style.left = -outWidth + inWidth + "px";
	operateCtn.querySelector(".exchange").classList.toggle("alternate");
	
	// 2 交换
	var that = this;
	setTimeout(function(){
		var tmpLang = that.originLang,
			tmpId   = that.originId;
		that.originLang = that.targetLang;
		that.originId   = that.targetId;
		that.targetLang = tmpLang;
		that.targetId   = tmpId;
		that.render();
		operateCtn.classList.remove("exchanging");

		operateCtn.querySelector(".origin .in").style = "";
		operateCtn.querySelector(".target .in").style = "";
		
		that.exchangeStatus = false;
	}, 500);
};

IolLanguageSelect.prototype.lookParentByClassName = function(el, cname){
	// 检查元素el 或其某个父元素 是否含有class
	var tmpEl = el;
	while(tmpEl && tmpEl != document.documentElement){
		if(tmpEl.classList.contains(cname)){
			return tmpEl;
		}
		tmpEl = tmpEl.parentNode;
	}
	return false;
};

IolLanguageSelect.prototype.initEvent = function(){
	// 初始化事件
	var that = this,
		activeElem = null;		// 活动元素
	
	this.el.querySelector(".exchange").addEventListener("click", function(e){
		// 交换语言
		if(this.classList.contains("disabled")){
			e.stopPropagation();
			return false;
		}
		that.exchange();
		
		if(that.options.exchange && typeof(that.options.exchange) == "function"){
			that.options.exchange.apply(that);
		}
	});
	
	this.el.addEventListener("click", function(e){
		var eTar = e.target, 
			langBtn = that.lookParentByClassName(eTar, "lang-btn");
			
		if(langBtn){
			// 显示语言列表
			e.stopPropagation();
			if(langBtn.classList.contains("js-origin")){
				that.showOriginLangs();
			}else if(langBtn.classList.contains("js-target")){
				that.showTargetLangs();
			}
			activeElem = true;
		}
		
		if(eTar.classList.contains("lang")){
			// 选择语言
			e.stopPropagation();
			if(eTar.classList.contains("disabled")){ return false; }
			
			var language = eTar.innerHTML,
				languageId = parseInt(eTar.getAttribute("data-id"));
			if(that.activeLang == "origin"){
				that.originLang = language;
				that.originId = languageId;
			}else if(that.activeLang == "target"){
				that.targetLang = language;
				that.targetId = languageId;
			}
			
			that.render();
			that.closeLangs();
			
			if(that.options.selectLang && typeof(that.options.selectLang) == "function"){
				that.options.selectLang.apply(that);
			}
		}else if(that.lookParentByClassName(eTar, "language-list") || that.lookParentByClassName(eTar, "langs-often")){
			// 点击语言选择面板其他地方时, 不关闭面板
			e.stopPropagation();
		}
		
		return false;
	});
	
	document.body.addEventListener("click", function(e){
		if(e.target.classList.contains("iol-btn-expand")){
			// 收缩, 展开
			var par = e.target.parentNode, sib;
			if(par.classList.contains("iol-show")){
				par.querySelector(".iol-btn-expand").innerHTML = "展开";
				par.classList.remove("iol-show");
			}else {
				par.querySelector(".iol-btn-expand").innerHTML = "收起";
				par.classList.add("iol-show");
			}
			

			// var clickTar = null;
			// if(par.classList.contains("origin-langs")){
			// 	clickTar = ".js-origin";
			// }else{
			// 	clickTar = ".js-target";
			// }
			// that.el.querySelector(clickTar).click();
			return false;
		}

		if(activeElem){
			that.closeLangs();
			activeElem = false;
		}
	});
};

window.IolLanguageSelect = IolLanguageSelect;
